<template>
  <div class="upload-cropper">
    <div class="upload-cropper-image" :style="imgContainerStyle">
      <span v-if="img_url" class="upload-cropper-close" @click="delImg">×</span>
      <img v-if="img_url" :src="img_url" />
    </div>
    <div class="upload-cropper-text" :style="{ width: imgContainerStyle.width }" @click="openVueCropper">
      {{ tipsText }}
    </div>
  </div>
</template>

<script>
import { dialog } from '../antd-dialog/index.js';

export default {
  name: 'upload-image-cropper',
  emits: ['update:modelValue', 'change'],
  props: {
    modelValue: { type: String, default: '' },
    tipsText: { type: String, default: '上传图片' },
    setting: { type: Object, default: () => ({ autoCropWidth: 160, autoCropHeight: 90 }) },
  },
  data() {
    return {
      img_url: '',
    };
  },
  computed: {
    imgContainerStyle() {
      const { autoCropWidth = 0, autoCropHeight = 0, borderWidth = 0, borderHeight = 0 } = this.setting;
      return {
        width: Number(borderWidth || autoCropWidth) + 2 + 'px',
        height: Number(borderHeight || autoCropHeight) + 2 + 'px',
      };
    },
  },
  mounted() {
    this.$watch(
      () => this.modelValue,
      () => {
        this.img_url = this.modelValue;
      },
      { immediate: true },
    );
  },
  methods: {
    output() {
      this.$emit('update:modelValue', this.img_url);
      setTimeout(() => {
        this.$emit('change', this.img_url);
      }, 0);
    },
    delImg() {
      this.img_url = '';
      this.output();
    },
    openVueCropper() {
      dialog({
        content: () => import('./vue-cropper.vue'),
        contentProps: {
          ...this.$attrs,
          setting: this.setting,
          onSuccess: (url) => {
            this.img_url = url;
            this.output();
          },
        },
        dialogProps: { title: '上传图片', footer: null, width: 'medium', bodyStyle: { padding: '24px' } },
      });
    },
  },
};
</script>

<style lang="less">
.upload-cropper {
  .upload-cropper-image {
    position: relative;
    border: 1px dashed #cccccc;
    img {
      width: 100%;
      height: 100%;
    }
    .upload-cropper-close {
      position: absolute;
      top: 0;
      right: 0;
      color: #d5d5d5;
      font-size: 28px;
      line-height: 0.7;
      cursor: pointer;
    }
  }
  .upload-cropper-text {
    color: #409eff;
    text-align: center;
    cursor: pointer;
  }
}
</style>
